package com.ys.filelib.filedialog;

import android.content.Context;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import com.ys.filelib.R;
import com.ys.filelib.databinding.FilelibDialogLoginFtpBinding;
import com.ys.filelib.filedialog.ftp.FTPHelper;
import com.ys.filelib.filedialog.loader.Executor;


class LoginFTPDialog extends MyDialog {

    private FilelibDialogLoginFtpBinding mView;
    private OnFTPListener mListener;
    private FTPHelper mFTPHelper;
    private ProgressView mProgressView;

    public LoginFTPDialog(Context context) {
        super(context);
        mProgressView = new ProgressView(context);
    }

    @Override
    protected View getView() {
        mView = FilelibDialogLoginFtpBinding.inflate(getInflater());
        initVew();
        return mView.getRoot();
    }

    @Override
    protected void onStart() {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.width = 1080;
    }

    private void initVew() {
        mFTPHelper = null;
        View.OnClickListener listener = v -> {
            if (v == mView.tvCancel) {
                dismiss();
            }
            if (v == mView.tvOk) {
                String ip = mView.etIp.getText().toString().trim();
                String port = mView.etPort.getText().toString().trim();
                String user = mView.etUser.getText().toString().trim();
                String passw = mView.etPassw.getText().toString().trim();
                if (ip.isEmpty() || port.isEmpty()) {
                    return;
                }
                if (mFTPHelper == null) {
                    mFTPHelper = new FTPHelper();
                }
                v.setEnabled(false);
                mProgressView.show();
                Executor.execute(() -> {
                    int intPort = Integer.parseInt(port);
                    boolean bool = mFTPHelper.connectFtp(ip, intPort, user, passw);
                    runOnUI(()-> {
                        v.setEnabled(true);
                        mProgressView.dismiss();
                        if (bool) {
                            if (mListener != null) {
                                mListener.onFtp(mFTPHelper);
                            }
                            dismiss();
                        } else {
                            Toast.makeText(getContext(), getContext().getString(R.string.str_login_fail), Toast.LENGTH_SHORT).show();
                        }
                    });
                });
            }
        };
        mView.tvOk.setOnClickListener(listener);
        mView.tvCancel.setOnClickListener(listener);
    }

    public void setFTPListener(OnFTPListener listener) {
        this.mListener = listener;
    }

    public interface OnFTPListener {
        void onFtp(FTPHelper helper);
    }
}
